package com.itheima.controller;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.itheima.utils.QRCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取微信小程序码相关
 */
@Slf4j
@RestController
@RequestMapping("qrcode")
public class QRCodeController {

    @Autowired(required = false)
    private RestTemplate restTemplate;

    /**
     * 获取小程序码的接口URL
     */
    private static final String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN";

    /**
     * 获取小程序的二维码(小太阳)字节数组
     */
    public byte[] getQrcodeByteArray(String url, Map<String, Object> body) throws Exception {
        File file = new File("C:\\Users\\yuanh\\Desktop\\logo\\太阳码.png");
        FileInputStream fileInputStream = new FileInputStream(file);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int n = 0;
        while (-1 != (n = fileInputStream.read(buffer))) {
            outputStream.write(buffer, 0, n);
        }
        return outputStream.toByteArray();
        // return restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(body, null), byte[].class).getBody();
    }

    /**
     * 生成微信小程序码(以流的形式直接下载到浏览器)
     */
    @GetMapping(value = "/create/miniCode")
    public void getWechatQrcode(Long activityId, HttpServletResponse response) throws Exception {
        Map<String, Object> body = new HashMap<>();

        /**
         * 扫码进入的小程序页面路径，根路径前不要填加
         * 不能携带参数（参数请放在scene字段里），如果不填写这个字段，默认跳主页面
         */
        body.put("path", "pages/index/index?activityId=" + activityId);

        /**
         * 要打开的小程序版本
         * 正式版为 "release" 体验版为 "trial"，开发版为 "develop" 默认是正式版。
         */
        body.put("env_version", "trial");


        byte[] byteArray = getQrcodeByteArray(url, body);
        InputStream inputStream = new ByteArrayInputStream(byteArray);

        // 替换太阳码中间的logo
        byteArray = changLogo(inputStream);
        InputStream is = new ByteArrayInputStream(byteArray);
        String name = "签到小程序码";

        //设置请求头
        response.setContentType("image/png");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(name + ".png", "UTF-8"));
        //response.setHeader("Content-Type", "application/octet-stream");

        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = is.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }
        is.close();
        outputStream.close();
    }

    private byte[] changLogo(InputStream inputStream) {
        BufferedImage bdground = null;
        BufferedImage logo = null;
        try {
            bdground = ImageIO.read(inputStream);
            logo = ImageIO.read(new File("C:\\Users\\yuanh\\Desktop\\logo\\logo1.jpg"));
            Graphics2D g = bdground.createGraphics();
            g.drawImage(logo, 78, 78, 124, 124, null);
            g.dispose();
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            ImageIO.write(bdground, "jpg", result);
            result.flush();
            byte[] resultByte = result.toByteArray();
            return resultByte;
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (bdground != null) {
                bdground.getGraphics().dispose();
                bdground = null;
            }
            if (logo != null) {
                logo.getGraphics().dispose();
                logo = null;
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 生成二维码(以流的形式直接下载到浏览器)
     * type 二维码的类型，为了演示效果，1跳百度的，2是跳京东
     */
    @GetMapping(value = "/create/activity-code")
    public void getCode(int type, HttpServletResponse response) throws Exception {
        String name = "签到二维码";

        // 设置响应流信息
        response.setContentType("image/png");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //设置请求头
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(name + ".jpg", "UTF-8"));
        response.setHeader("Content-Type", "application/octet-stream");

        OutputStream outputStream = response.getOutputStream();

        // type是1，生成活动详情、报名的二维码，type是2，生成活动签到的二维码
        String content = (type == 1 ? "http://www.baidu.com" : "http://www.jd.com");

        BufferedImage generate = QrCodeUtil.generate(
                content, // 二维码内容
                QrConfig.create()
                        .setImg("C:\\Users\\yuanh\\Desktop\\logo\\logo1.jpg") // 附带logo
                        .setRatio(4) // 二维码中间logo的缩放比例大小, 默认6
        );
        ImgUtil.write(generate, "jpg", outputStream);
        outputStream.flush();
        outputStream.close();
    }
}
